﻿using System;
using System.Configuration;
using System.Web.Mvc;

namespace Viettel.VOFFICE.Web.Helpers
{
    /// <summary>
    /// Custom gói tin trả về cho 1 action request tải tệp
    /// </summary>
    public class DownloadResult : ActionResult
    {
        public DownloadResult(){}

        /// <summary>
        /// Khởi tạo
        /// </summary>
        /// <param name="virtualFilePath">Đường dẫn tương đối của file dạng /Assets/lib/a.jpg</param>
        /// <param name="fileDownloadName">Tên file trả về client</param>
        public DownloadResult(string virtualFilePath, string fileDownloadName)
        {
            var rootFoler = ConfigurationManager.AppSettings["WebUploadRootFolder"];
            if (string.IsNullOrWhiteSpace(rootFoler))
            {
                throw new Exception("Can not find root folder.");
            }
            this.DiskFilePath = rootFoler + virtualFilePath;
            this.FileDownloadName = fileDownloadName;
        }

        public string DiskFilePath { get; set; }

        public string FileDownloadName { get; set; }

        /// <summary>
        /// Override hàm trả về.
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (!String.IsNullOrEmpty(FileDownloadName))
            {
                context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + this.FileDownloadName);
            }
            context.HttpContext.Response.TransmitFile(this.DiskFilePath);
        }
    }
}